if(window.location.pathname.indexOf("commonDetailPage") > -1){
    $(".next-step").remove();
    $(".cancleEditBtn").show();
    console.log($(".form-box").attr("id"))
}else {
    $(".cancleEditBtn").remove();
}
if(thisProviderId&&thisProviderId!=""){
    renderDetail();//详情信息渲染
    console.log(thisProviderId)
}
$(".detail-form").Validform({
    tiptype: 2,
    callback: function (form) {
        saveAuthenticationInfo();
        return false;
    }
});
/*保存数据*/
function saveAuthenticationInfo(stepFn){
    var params = {
        "annualSales": $(".annualSales").val(),//年销售额
        "areaId": $(".areaId").val(),//注册地址-区id
        "areaName": $(".areaId option:selected").text(),//注册地址-区名称
        "brand": $(".brand").val(),//经营品牌
        "businessLicenseImgUrl": $(".businessLicenseImgUrl").attr("imgurldata"),//营业执照
        "cityId": $(".cityId").val(),//注册地址-市id
        "cityName": $(".cityId option:selected").text(),// 注册地址-市名称
        "companyId": $(".companyId").attr("data-id"),//主维护单位id
        "companyName": $(".companyId").val(),//主维护单位名称
        "countyId": $(".countyId").val(),//注册地址-县id
        "countyName": $(".countyId option:selected").text(),//注册地址-县名称
        "createUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,//创建人
        "creditCode": $(".creditCode").val(),//统一社会信用代码
        "detailAddress": $(".detailAddress").val(),//详细地址
        "legalPersonCardEffectiveTime": $(".legalPersonCardEffectiveTime").val(),//证件生效日期
        "legalPersonCardImgUrl1": $(".legalPersonCardImgUrl1").attr("imgurldata"),//法人证件照1
        "legalPersonCardImgUrl2": $(".legalPersonCardImgUrl2").attr("imgurldata"),// 法人证件照2
        "legalPersonCardInvalidTime": $(".legalPersonCardInvalidTime").val(),//证件失效日期
        "legalPersonCardNumber": $(".legalPersonCardNumber").val(),//法人证件号
        "legalPersonName": $(".legalPersonName").val(),//法人姓名
        "linkManName": $(".linkManName").val(),// 联系人名称
        "linkManPhone": $(".linkManPhone").val(),//联系人手机号
        "longValidityed": $(".longValidityed").prop("checked") ? 1 : 0,//是否长期有效（0:否，1:是）
        "manageRegionId": $(".manageRegionId").attr("data-id"),// 管理区域id
        "manageRegionName": $(".manageRegionId").val(),//管理区域名称
        "name": $(".name").val(),//服务商(公司)名称
        "number": $(".name").attr("data-number"),//服务商(公司)名称
        "provinceId": $(".provinceId").val(),//注册地址-省id
        "provinceName": $(".provinceId option:selected").text(),//注册地址-省名称
        "updateUserName": JSON.parse(decodeURIComponent(web.readCookie("loginData"))).user.name,//修改人
        manageSaleMan: $("input[name='manageSaleMan']").val(), //销售负责人
        manageSaleManPhone: $("input[name='manageSaleManPhone']").val() //销售负责人手机号
    }
    var judgmentFieldObj = {
        // "annualSales":"请输入年销售额",
        "companyName":"请选择主维护单位",
        "manageRegionName":"请选择管理区域",
        "linkManPhone":"请输入联系人手机号",
        "linkManName":"请输入联系人姓名",
        "legalPersonCardImgUrl2":"请上传身份证正反面",
        "legalPersonCardImgUrl1":"请上传身份证正反面",
        "legalPersonCardNumber":"请输入法定代表人证件号",
        "legalPersonName":"请输入法定代表人姓名",
        "detailAddress":"请输入注册地址",
        // "countyName":"注册地址-县",
        "areaName":"请选择注册地址-区",
        "cityName":"请选择注册地址-市",
        "provinceName":"请选择注册地址-省",
        "businessLicenseImgUrl":"请上传营业执照",
        "creditCode":"请输入统一社会信用代码",
        "name":"请输入公司名称",
        "manageSaleMan" : "请输入销售负责人",
        "manageSaleManPhone" : "请输入销售负责人手机号",
    }
    if (params.manageSaleMan.length > 10) {
        $.Huimodalalert("销售负责人最多支持输入10个长度",2000);
        return false;
    }
    if (params.manageSaleManPhone.length > 11) {
        $.Huimodalalert("销售负责人手机号最多支持输入11位",2000);
        return false;
    }
    if((thisProviderId&&thisProviderId!="")||window.location.pathname.indexOf("commonDetailPage") > -1){
        var doUrl = root.approvedServiceProviders.updateProviderBaseById;
        params.id = thisProviderId;
    }else {
        var doUrl = root.approvedServiceProviders.addProviderBase;
    }
    console.log(params)
    var isContinue = nullValueJudgmentFn(params,judgmentFieldObj);
    if(!isContinue){
        return false;
    }else {
        if ((params.legalPersonCardInvalidTime==""||params.legalPersonCardEffectiveTime=="")&&params.longValidityed==0){
            $.Huimodalalert("请输入证件有效期",2000);
            return false;
        }
    }
    var countyElArrLength = $(".countyId").children().length;
    console.log(countyElArrLength)
    if(countyElArrLength > 1&&params.countyId==-1){
        $.Huimodalalert("请输入注册地址-县",2000);
        return false;
    }
    web.doAjax(doUrl, 'post',params, function (data) {
        if(data.code == 0){
            console.log(data);
            $.Huimodalalert(data.msg,2000);
            if(window.location.pathname.indexOf("commonDetailPage") > -1){
                $(".form-box").load("detailPackage/authenticationInfoDetail.html");
            }
            if(window.location.pathname.indexOf("commonAddPage") > -1&&(!thisProviderId||thisProviderId=="")){
                thisProviderId = data.data;
            }
            if(stepFn){
                console.log(stepFn)
                eval(stepFn)
            }
        }else {
            $.Huimodalalert(data.msg,2000);
        }
    },1);
}
/*图片上传*/
var businessLicenseImgFormData = new FormData();
var legalPersonCardImgUrl1FormData = new FormData();
var legalPersonCardImgUrl2FormData = new FormData();
function addBtn(elId) {
    if(elId=="businessLicenseImgFileUp"){
        businessLicenseImgFormData.delete("file")
        var fileUpEl = document.getElementById('businessLicenseImgFileUp') ;
        fileUpEl.outerHTML=fileUpEl.outerHTML;
        $("#businessLicenseImgFileUp").trigger('click');
    }else if(elId == "legalPersonCardImgUrl1FileUp"){
        legalPersonCardImgUrl1FormData.delete("file")
        var fileUpEl = document.getElementById('legalPersonCardImgUrl1FileUp') ;
        fileUpEl.outerHTML=fileUpEl.outerHTML;
        $("#legalPersonCardImgUrl1FileUp").trigger('click');
    }else if(elId == "legalPersonCardImgUrl2FileUp"){
        legalPersonCardImgUrl2FormData.delete("file")
        var fileUpEl = document.getElementById('legalPersonCardImgUrl2FileUp') ;
        fileUpEl.outerHTML=fileUpEl.outerHTML;
        $("#legalPersonCardImgUrl2FileUp").trigger('click');
    }
}

function putDataToPage(e,elId) {
    var limitSize = 5*1024*1024;
    for (var i = 0; i < e.target.files.length; i++) {
        console.log(e.target.files)
        var file = e.target.files.item(i);
        if (!(/^image\/.*$/i.test(file.type))) {
            $.Huimodalalert('请上传5M以内的图片',2000);
            return; //不是图片 就跳出这一次循环
        }
        if(file.size>limitSize){
            $.Huimodalalert('请上传5M以内的图片',2000);
            return;
        }
        //实例化FileReader API
        var freader = new FileReader();
        freader.readAsDataURL(file);
        freader.onload = function (e) {
            // $("#myImg").attr("src", e.target.result);
        }
    }
    uploadImg(elId);
}
function uploadImg(elId){
    if(elId == "businessLicenseImgFileUp"){
        businessLicenseImgFormData.set('file', $("#businessLicenseImgFileUp")[0].files[0]);
        $.ajax({
            url: root.inter.imgUpload,
            cache: false, //禁用缓存
            type: "POST",
            processData : false,
            contentType : false,
            data: businessLicenseImgFormData,
            success: function (data) {
                $(".businessLicenseImgUrl").attr("src", data[0].fullPath);
                $(".businessLicenseImgUrl").attr("imgUrlData", data[0].fullPath);
                $(".businessLicenseImgFileUpBtn").html("重新上传");
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })
    }else if(elId == "legalPersonCardImgUrl1FileUp"){
        legalPersonCardImgUrl1FormData.set('file', $("#legalPersonCardImgUrl1FileUp")[0].files[0]);
        $.ajax({
            url: root.inter.imgUpload,
            cache: false, //禁用缓存
            type: "POST",
            processData : false,
            contentType : false,
            data: legalPersonCardImgUrl1FormData,
            success: function (data) {
                $(".legalPersonCardImgUrl1").attr("src", data[0].fullPath);
                $(".legalPersonCardImgUrl1").attr("imgUrlData", data[0].fullPath);
                $(".legalPersonCardImgUrl1FileUpBtn").html("重新上传");
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })
    }else if(elId == "legalPersonCardImgUrl2FileUp"){
        legalPersonCardImgUrl2FormData.set('file', $("#legalPersonCardImgUrl2FileUp")[0].files[0]);
        $.ajax({
            url: root.inter.imgUpload,
            cache: false, //禁用缓存
            type: "POST",
            processData : false,
            contentType : false,
            data: legalPersonCardImgUrl2FormData,
            success: function (data) {
                $(".legalPersonCardImgUrl2").attr("src", data[0].fullPath);
                $(".legalPersonCardImgUrl2").attr("imgUrlData", data[0].fullPath);
                $(".legalPersonCardImgUrl2FileUpBtn").html("重新上传");
            },
            error: function () {
                $.Huimodalalert('失败！',2000);
            }
        })
    }
}

function selectTimeFn() {
    $(".longValidityed").prop("checked",false);//选择生效日期时清除长期有效
}
timeSet(".legalPersonCardEffectiveTime",".legalPersonCardInvalidTime","YYYY-MM-DD",selectTimeFn,selectTimeFn);
function isLongValidityed(el) {
    if($(el).prop("checked")){
        $(".legalPersonCardEffectiveTime").val("");
        $(".legalPersonCardInvalidTime").val("");
    }
}
/*四级地址选择*/
if(window.location.pathname.indexOf("commonAddPage") > -1&&!getQueryString("type")){
    queryAddress('','provinceId');
}
function queryAddress(curTargetClass, nextTargetClass, id, parentId) {
    if(curTargetClass=="provinceId"){
        $(".cityId").val(-1);
        $(".cityId").html('<option value="-1">请选择</option>');
        $(".areaId").val(-1);
        $(".areaId").html('<option value="-1">请选择</option>');
        $(".countyId").val(-1);
        $(".countyId").html('<option value="-1">请选择</option>');
    }else if(curTargetClass=="cityId"){
        $(".areaId").val(-1);
        $(".areaId").html('<option value="-1">请选择</option>');
        $(".countyId").val(-1);
        $(".countyId").html('<option value="-1">请选择</option>');
    }
    if(curTargetClass==""){
        var user_data = {
            parentCode: ""
        }
    }else {
        if(parentId){
            var user_data = {
                parentCode: parentId
            }
        }else {
            var user_data = {
                parentCode: $("."+curTargetClass).val()
            }
        }
    }
    web.doAjax(root.member.getLowerAddress,'post',user_data, function (data) {
        if(data.errorCode == "0"){
            var addressHtml = '<option value="-1">请选择</option>';
            data.list.forEach((item) => {
                if(id&&item.code==id){
                    addressHtml += '<option value="'+item.code+'" selected>'+item.name+'</option>';
                }else {
                    addressHtml += '<option value="'+item.code+'">'+item.name+'</option>';
                }

            });
            $("."+nextTargetClass).html(addressHtml);
        }
    });
}
/*认证信息*/
//获取认证信息详情
function renderDetail() {
    var getAuthenticationDetail = getAuthenticationDetailPro(thisProviderId);
    //获取详情信息
    getAuthenticationDetail.then(
        (res) => {
            if (res){
                renderForm(res);
            }
        },  // 成功
        (err) => {console.log(err)} // 失败
    )
}
/*详情信息渲染*/
function renderForm(res){
    $(".annualSales").val(res.annualSales);//年销售额
    queryAddress('cityId','areaId',res.areaId,res.cityId);//注册地址-区id
    $(".brand").val(res.brand);//经营品牌
    $(".businessLicenseImgUrl").attr("imgurldata",res.businessLicenseImgUrl);//营业执照
    $(".businessLicenseImgUrl").attr("src",res.businessLicenseImgUrl);//营业执照
    if(res.businessLicenseImgUrl&&res.businessLicenseImgUrl!=""){
        $(".businessLicenseImgFileUpBtn").html("重新上传");
    }
    queryAddress('provinceId','cityId',res.cityId,res.provinceId);//注册地址-市id
    $(".companyId").val(res.companyName);//主维护单位名称
    $(".companyId").attr("data-id",res.companyId);//主维护单位id
    queryAddress('areaId','countyId',res.countyId,res.areaId);//注册地址-县id
    $(".creditCode").val(res.creditCode);//统一社会信用代码
    $(".detailAddress").val(res.detailAddress);//详细地址
    $(".legalPersonCardEffectiveTime").val(dealNull(res.legalPersonCardEffectiveTime));//证件生效日期
    $(".legalPersonCardImgUrl1").attr("imgurldata",res.legalPersonCardImgUrl1);//法人证件照1
    $(".legalPersonCardImgUrl1").attr("src",res.legalPersonCardImgUrl1);//法人证件照1
    if(res.legalPersonCardImgUrl1&&res.legalPersonCardImgUrl1!=""){
        $(".legalPersonCardImgUrl1FileUpBtn").html("重新上传");
    }
    $(".legalPersonCardImgUrl2").attr("imgurldata",res.legalPersonCardImgUrl2);// 法人证件照2
    $(".legalPersonCardImgUrl2").attr("src",res.legalPersonCardImgUrl2);// 法人证件照2
    if(res.legalPersonCardImgUrl2&&res.legalPersonCardImgUrl2!=""){
        $(".legalPersonCardImgUrl2FileUpBtn").html("重新上传");
    }
    $(".legalPersonCardInvalidTime").val(dealNull(res.legalPersonCardInvalidTime));//证件失效日期
    $(".legalPersonCardNumber").val(res.legalPersonCardNumber);//法人证件号
    $(".legalPersonName").val(res.legalPersonName);//法人姓名
    $(".linkManName").val(res.linkManName);// 联系人名称
    $(".linkManPhone").val(res.linkManPhone);//联系人手机号
    $(".longValidityed").prop("checked",res.longValidityed==1?true:false);//是否长期有效（0:否，1:是）
    $(".manageRegionId").val(res.manageRegionName);// 管理区域名称
    $(".manageRegionId").attr("data-id",res.manageRegionId);//管理区域id
    $(".name").val(res.name);//服务商(公司)名称
    $(".name").attr("data-number",res.number);//服务商(公司)代码
    $(".number").html(res.number);//服务商(公司)代码
    $("input[name='manageSaleMan']").val(res.manageSaleMan); //销售负责人
    $("input[name='manageSaleManPhone']").val(res.manageSaleManPhone); //销售负责人手机号
    queryAddress('','provinceId',res.provinceId)
};
/*管理区域*/
function getAreaListFn(name){
    var params = {
        "areaName":name,
    }
    web.doAjax(root.approvedServiceProviders.findAreaListByName,'post',params, function (data) {
        if(data.code == "0") {
            $(".manageRegionList").css("display","block");
            if(data.data.length == 0) {
                var manageRegionHtml = '<li class="clearfix pl-10 mb-5">无数据</li>';
                $(".manageRegionList").html(manageRegionHtml);
            } else {
                var manageRegionHtml = '';
                data.data.forEach((item) => {
                    manageRegionHtml += "<li class='clearfix pl-10 mb-5' onclick='selectManageRegionItem("+JSON.stringify(item)+")'>"+item.areaName+"</li>"
                })
                $(".manageRegionList").html(manageRegionHtml);
            }
        }
    },2);
}
/*主维护单位（客户归属）*/
function searchOrgListFn(name) {
    var params = {
        "pageSize":100,
        "pageNum":1,
        "organizationName":name
    }
    web.doAjax(root.member.newSearchOrgList,'post',params, function (data) {
        if(data.code == "0") {
            $(".companyList").css("display","block");
            if(data.data.length == 0) {
                var companyHtml = '<li class="clearfix pl-10 mb-5">无数据</li>';
                $(".companyList").html(companyHtml);
            } else {
                var companyHtml = '';
                data.data.forEach((item) => {
                    companyHtml += "<li class='clearfix pl-10 mb-5' onclick='selectItem("+JSON.stringify(item)+")'>"+item.companyName+"</li>"
                })
                $(".companyList").html(companyHtml);
            }
        }
    },1);
}
$(document).bind("click", function(e) {
    //id为menu的是菜单，id为open的是打开菜单的按钮
    if($(e.target).closest(".companyList").length == 0 && $(e.target).closest(".companyId").length == 0) {
        //点击id为menu之外且id不是不是open，则触发
        $(".companyList").hide();
    }
    if($(e.target).closest(".manageRegionList").length == 0 && $(e.target).closest(".manageRegionId").length == 0){
        $(".manageRegionList").hide();
    }
});
function selectManageRegionItem(data) {
    $(".manageRegionId").val(data.areaName).attr("data-id",data.areaId);
    $(".manageRegionList").hide();
}
function selectItem(data) {
    $(".companyId").val(data.companyName).attr("data-id",data.companyId);
    $(".companyList").hide();
}
